﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using FriendsNearby.Services.Entities;
using InSTEDD.Labs.Geo;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection;

namespace FriendsNearby.Services
{
	public class LocationService : ILocationService
	{
		DataAccess dataAcess;
		IPeopleNearbyService peopleNearbyService;

		public LocationService(DataAccess dataAcess)
		{
			this.dataAcess = dataAcess;
		}

		public void SetPeopleNearbyService(IPeopleNearbyService peopleNearbyService)
		{
			this.peopleNearbyService = peopleNearbyService;
		}


		#region ILocationService Members

		public LocationInfo GetCurrentLocation(Guid userID)
		{
			return dataAcess.GetCurrentUserLocation(userID);
		}

		[Tag("CacheShortTerm")]
		public LocationInfo GetLocationAt(Guid userID, DateTime pointInTime)
		{
			UserLocationHistory lastLocationChange = dataAcess.GetUserLocation(userID, pointInTime);
			LocationInfo info = new LocationInfo();
			if (lastLocationChange != null)
			{
				info.UserID = userID;
				info.Location = new LatLong(lastLocationChange.Lat, lastLocationChange.Long);
				info.When = lastLocationChange.Timestamp;
			}
			return info;
		}

		public LocationInfo GetLastLocationInfo(Guid userID)
		{
			LatLong location;
			DateTime date;
			if (dataAcess.GetLastLocationInfo(userID, out location, out date))
			{
				return new LocationInfo() { UserID = userID, Location = location, When = date };
			}
			else
			{
				return null;
			}
		}

		public void SetCurrentLocation(Guid userID, LatLong location)
		{
			//Temporarily disabled SocialLog
			//IEnumerable<PersonNearby> personNearbyBefore = peopleNearbyService.GetContacts(userID, QueryContactsKind.Nearby);
			dataAcess.UpdateUserLocation(userID, location);

			//IEnumerable<PersonNearby> personNearbyAfter = peopleNearbyService.GetContacts(userID, QueryContactsKind.Nearby);

			//dataAcess.AddSocialEntryLog(userID, DateTime.Now, personNearbyBefore != null ? personNearbyBefore.Count() : 0, personNearbyAfter != null ? personNearbyAfter.Count() : 0);
		}

		public DateTime GetLastNotificationDate(Guid userID)
		{
			return dataAcess.GetLastNotificationDate(userID);
		}

		public void SaveLastNotificationDate(Guid userID, DateTime dateTime)
		{
			dataAcess.SaveLastNotificationDate(userID, dateTime);
		}

		public IEnumerable<Guid> GetMovedUsers(DateTime since)
		{
			return dataAcess.GetMovedUsers(since);
		}

		#endregion
	}
}
